<template>
	<div style="width: 100%">
		<el-upload
			:data="uploadData"
			:headers="uploadHeader"
			:action="uploadUrl"
			:show-file-list="false"
			:on-success="handleAvatarSuccess"
			:before-upload="
				function (file) {
					return beforeUpload(file, index);
				}
			"
		>
			<el-image v-if="img" :src="img" class="def_img" mode="widthFix" />
			<el-icon v-else class="avatar-uploader-icon avatar-uploader">
				<Plus />
			</el-icon>
		</el-upload>
	</div>
</template>

<script setup lang="ts" name="upload">
import { reactive, computed, nextTick, ref, watch, onBeforeMount } from 'vue';
import { ElMessage } from 'element-plus';
import { Session } from '/@/utils/storage';

const uploadUrl = ref(import.meta.env.VITE_API_URL + 'common/upload');
// 定义父组件传过来的值
const props = defineProps({
	// 列表内容
	fileCode: {
		type: String,
		default: () => 'IMG',
	},
	index: {
		type: Number,
		default: () => 0,
	},
	fileUrl: {
		type: String,
		default: () => '',
	},
});
const img = ref('');
const uploadData = ref({
	fileCode: props.fileCode,
});

watch(
	() => props.fileUrl,
	(val) => {
		img.value = props.fileUrl;
	}
);

onBeforeMount(() => {
	img.value = props.fileUrl;
});

const uploadHeader = ref({
	'auth-token': `${Session.get('token')}`,
});

function beforeUpload(file, index) {}

function handleAvatarSuccess(res: any) {
	if (res.code == 200) {
		// list.value.data[clickIndex].img = res.data.fileUrl;
		img.value = res.data.fileUrl;
		emit('handleAvatarSuccess', {
			url: res.data.fileUrl,
			index: props.index,
		});
	} else {
		ElMessage.error(res.msg);
	}
}

// 定义子组件向父组件传值/事件
const emit = defineEmits(['handleAvatarSuccess']);
</script>

<style scoped lang="scss">
.avatar-uploader {
	// width: 200px;
	height: 60px;
	border: 1px dashed #dcdfe6;
	border-radius: 10px;
	display: flex;
	text-align: center;
	justify-content: center;
}

.avatar-uploader-icon {
	min-width: 120px;
	height: 60px;
}
.def_img {
	width: 100%;
	// border-radius: 10px;
	height: 60px;
}
</style>
